/* Bento Studio / 2012 / Uniflow / v1.1a
 *
 * Uniflow is an Unity clone of a well-known 3D gallery UI.
 *
 * UniflowZoomBackground:
 * This component sets & fades a black background when zooming on a thumbnail.
 *
 * v1.0
 * 	Initial Release
 * v1.1
 * 	Added fully working zoom, handlers.
 * 	Fixed weird zoom rotation effect (by computing shortest rotation)
 * 	Fixed Editor Inspector bug (gallery set as dirty at every frame)
 * v1.2
 *	Minor bug fix
 * 	Reuploading to Unity Asset Store...
 */

using UnityEngine;
using System.Collections;

public class UniflowZoomBackground : MonoBehaviour {

	private float fNearPlaneEpsilon = 0.1f;

	private UIEffectColor m_rUIEffectColorFader;

	void Awake( )
	{
		// Gallery background Initialization
		UIEffectColor rUIEffectColorFader = gameObject.GetComponent<UIEffectColor>( ) as UIEffectColor;

		if( rUIEffectColorFader == null )
		{
			rUIEffectColorFader = gameObject.AddComponent<UIEffectColor>( ) as UIEffectColor;
		}

		rUIEffectColorFader.Init( );
		rUIEffectColorFader.colorName = "_Color";
		rUIEffectColorFader.colorIn = Color.clear;
		rUIEffectColorFader.colorOut = Color.black;
		rUIEffectColorFader.easing = gkInterpolate.EaseType.EaseOutCirc;
		rUIEffectColorFader.effectEndedDelegate = new UIEffectTemplate.EffectEndedDelegate( this.OnFadeEnd );

		m_rUIEffectColorFader = rUIEffectColorFader;

		Camera rMainCamera = Camera.mainCamera;
		float fDistanceFromMainCamera = rMainCamera.nearClipPlane + fNearPlaneEpsilon;

		// Computes plane scale from camera frustum width / height in order to make it "fullscreen"
		Vector3 f3Scale = transform.localScale;
		f3Scale.x = UniflowUtils.CameraFrustumWidthAtDistance( fDistanceFromMainCamera );
		f3Scale.y = UniflowUtils.CameraFrustumHeightAtDistance( fDistanceFromMainCamera );

		transform.localScale = f3Scale;

		// Computes position/rotation
		Quaternion oCurrentLocalRotation = transform.localRotation;
		transform.position = rMainCamera.transform.position + fDistanceFromMainCamera * rMainCamera.transform.forward;
		transform.parent = rMainCamera.transform;
		transform.localRotation = oCurrentLocalRotation;

		gameObject.active = false;
	}

	public void Init( UniflowGallery a_rUniflowGallery )
	{
		m_rUIEffectColorFader.duration = a_rUniflowGallery.zoomingDuration;
	}

	public void FadeIn( )
	{

		gameObject.active = true;

		m_rUIEffectColorFader.Play( );
	}

	public void FadeOut( )
	{
		gameObject.active = true;
		m_rUIEffectColorFader.PlayBackwards( );
	}

	private void OnFadeEnd( bool a_bEffectPlayedForward )
	{
		if( a_bEffectPlayedForward == false )
		{
			gameObject.active = false;
		}
	}
}
